﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Security.Application;

using Ec_System.Facade.Web;
using Ec_System.API;
using Ec_System.WebUI.Models;
using System.Web.Security;
using Newtonsoft.Json;
using Ec_System.Models.Web;

namespace Ec_System.WebUI.Areas.Web.Controllers
{
    public class CustomerController : Controller
    {

        CustomerFacade customerFacade = new CustomerFacade();

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UserReg()
        {
           
            return View();
        }
        [HttpPost]
        public ActionResult UserReg(FormCollection formCollection)
        {
            var validateCode = Sanitizer.GetSafeHtmlFragment(formCollection["ValidatorCode"]);
            if(validateCode != Session["ValidateCode"].ToString())
            {
                ViewBag.VCodeError = "验证码错误";
                return View(formCollection);
            }

            CustomerData customer = new CustomerData()
            {
                LoginID = Sanitizer.GetSafeHtmlFragment(formCollection["txt_uname"]),
                QQ = Sanitizer.GetSafeHtmlFragment(formCollection["txt_qq"]),
                Email = Sanitizer.GetSafeHtmlFragment(formCollection["txt_mail"]),
                Tel = Sanitizer.GetSafeHtmlFragment(formCollection["txt_tel"]),
                //用户MD5不可逆加密
                Password = MD5Helper.EncryptString(Sanitizer.GetSafeHtmlFragment(formCollection["txt_pass"]))
            };

            if(customerFacade.AddCustomer(customer) > 0)
            {
                return View("~/Areas/Web/Views/Customer/Success.cshtml");
            }
            else
            {
                return View("~/Areas/Web/Views/Customer/Failed.cshtml");
            }
        
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UserLogin()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UserLogin(FormCollection formCollection)
        {
            var validateCode = Sanitizer.GetSafeHtmlFragment(formCollection["ValidatorCode"]);
            if (validateCode != Session["ValidateCode"].ToString())
            {
                ViewBag.CodeErr = "验证码错误";
                return View(formCollection);
            }
           
            var model = customerFacade.UserLoginValidate(new CustomerData()
            {
                LoginID = Sanitizer.GetSafeHtmlFragment(formCollection["txt_uname"]),
                Email = Sanitizer.GetSafeHtmlFragment(formCollection["txt_uname"]),
                Password = Sanitizer.GetSafeHtmlFragment(formCollection["txt_pass"])
            }); 
            if (model != null)
            {
                //验证通过
                LoginViewModel loginModel = new LoginViewModel { LoginID = model.LoginID, RealName = model.RealName, UID = model.ID };
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "UserInfo", DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), true, JsonConvert.SerializeObject(loginModel));
                string hashTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie userCookies = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
                Response.Cookies.Add(userCookies);
                
                

                if(!string.IsNullOrWhiteSpace(Request["ReturnUrl"]))
                {
                    return Redirect(HttpUtility.UrlEncode(Request["ReturnUrl"]));
                }
                else
                {
                    return RedirectToAction("Index", "Home", new { area = "Web" });
                }
            }
            else
            {
                ViewBag.Info = "用户名或者密码错误";
                return View(formCollection);
            }          
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home", new { area = "Web" });
        }


        #region 检查Email是否存在
        [HttpPost]
        public JsonResult ValidateEmail()
        {
            string email = Sanitizer.GetSafeHtmlFragment(Request["txt_mail"]);
            bool result = customerFacade.IsContainEmail(email);

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 检查电话号码是否存在
        [HttpPost]
        public JsonResult ValidateTel()
        {
            string tel = Sanitizer.GetSafeHtmlFragment(Request["txt_tel"]);
            bool result = customerFacade.IsContainEmail(tel);

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 检查用户是否存在
        [HttpPost]
        public JsonResult ValidateUserName()
        {
            string name = Sanitizer.GetSafeHtmlFragment( Request["txt_uname"]);
            bool result = customerFacade.IsContainUsername(name);

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 验证码
        public ActionResult GetValidateCode()
        {
            ValidateCodeHelper obj = new ValidateCodeHelper();
            string code = obj.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] graf = obj.CreateValidateGraphic(code);
            return File(graf, @"image/jpeg");
        }
        #endregion

    }
}